import 'package:flutter/material.dart';
import 'package:zpub_plugin/com/zerogis/zpubPlugin/widget/WidgetStatefulBase.dart';
import 'package:flutter/widgets.dart';
import 'package:zpub_svr/zpub_svr.dart';
import 'package:zpub_bas/zpub_bas.dart';
import 'package:zpub_dbmanager/zpub_dbmanager.dart';
import 'package:zpub_dbmanager/com/zerogis/zpubDbManager/bean/Entity.dart';
import 'package:zpub_bas/com/zerogis/zpubbase/bean/Pager.dart';
import 'package:zpub_dbmanager/com/zerogis/zpubDbManager/bean/Fld.dart';

/*
 * 类描述：根据主子类型生成属性表格组件:不传ID则不请求网络生成属性
 * @param {Object 必传} major 主类型
 * @param {Object 必传} minor 子类型
 * @param {List   选传} list  属性对象【list和exp以下选其一】
 * @param {Object 选传} exp   查询条件【默认exp=id>0】
 * @param {Object 选传} types  类型
 * @param {Object 选传} vals   值
 * @param {Object 选传} separator 分隔符
 * @param {Object 选传} map 键值对
 * @param {Object 选传} plugin 插件对象
 * 作者：郑朝军 on 2020/5/25
 * 邮箱：1250393285@qq.com
 * 公司：武汉智博创享科技有限公司
 * 修改人：郑朝军 on 2020/5/25
 * 修改备注：
 */
class AttDataTable extends WidgetStatefulBase
{
  dynamic mInitPara;

  AttDataTable({Key key, this.mInitPara, plugin}) : super(key: key, plugin: plugin);

  State<StatefulWidget> createState()
  {
    return new AttDataTableState();
  }

  static String toStrings()
  {
    return "AttDataTable";
  }
}

class AttDataTableState extends WidgetBaseState<AttDataTable>
{
  /*
   * 分页对象
   */
  Pager m_pager = new Pager();

  /*
   * 查询过来的ismcard列表集合
   */
  List mList = new List();

  /*
   * 当前entity表对象
   */
  Entity mEntity;

  /*
   * 当前属性的列
   */
  List<Fld> mFldList;

  /*
   * 表格控件的数据源
   */
  DataSource mDataSource;

  /*
   * 表格控件每一页显示多少条[默认=10]
   */
  int mRowsPerPage = PaginatedDataTable.defaultRowsPerPage;

  /*
   * 被排序的位置
   */
  int _sortColumnIndex;

  /*
   * 升降序图标控制
   */
  bool _sortAscending = true;

  void initState()
  {
    super.initState();
    query(1);
  }

  void initData()
  {
    super.initData();
    // 初始化表格头部数据
    EntityManagerConstant entityManagerConstant = EntityManager.getInstance();
    FldManagerConstant fldManagerConstant = FldManager.getInstance();
    mEntity = entityManagerConstant.queryEntity(
        widget.mInitPara[DBFldConstant.FLD_MAJOR], widget.mInitPara[DBFldConstant.FLD_MINOR]);
    mFldList = fldManagerConstant.queryFldDispDep(mEntity.getTabatt());

    // 设置表格
    if(!CxTextUtil.isEmptyList(widget.mInitPara[BasMapKeyConstant.MAP_KEY_LIST]))
    {
      mRowsPerPage = widget.mInitPara[BasMapKeyConstant.MAP_KEY_LIST].length > mRowsPerPage ? mRowsPerPage : widget
          .mInitPara[BasMapKeyConstant.MAP_KEY_LIST].length;
      // 初始化表格具体里面的数据
      mDataSource = DataSource(widget.mInitPara[BasMapKeyConstant.MAP_KEY_LIST], mFldList);
    }
  }

  @override
  Widget build(BuildContext context)
  {
    return PaginatedDataTable(
      header: Text(mEntity.getNamec()),
      onSelectAll: mDataSource.selectAll,
      rowsPerPage: mRowsPerPage,
      columns: queryDataColumn(),
      source: mDataSource,
      sortColumnIndex: _sortColumnIndex,
      sortAscending: _sortAscending,);
  }

  @override
  void onNetWorkSucceed(String method, Object values)
  {
    if (method == 'queryPage')
    {

    }
    else
    {
      super.onNetWorkSucceed(method, values);
    }
  }

  /*
   * 查询属性
   */
  void query(int page)
  {
    if (CxTextUtil.isEmptyList(widget.mInitPara[BasMapKeyConstant.MAP_KEY_LIST]))
    {
      SvrAreaSvrService.queryPage(
          widget.mInitPara[DBFldConstant.FLD_MAJOR],
          widget.mInitPara[DBFldConstant.FLD_MINOR],
          widget.mInitPara[HttpParamKeyValue.PARAM_KEY_EXP] ?? DBExpConstant.EXP_ID_MORE_THAN_QUESTION,
          widget.mInitPara[HttpParamKeyValue.PARAM_KEY_TYPES] ?? DBExpTypesConstant.EXP_TYPES_I,
          widget.mInitPara[HttpParamKeyValue.PARAM_KEY_VALS] ?? BasStringValueConstant.STR_VALUE_ZERO,
          m_pager,
          this,
          page: page,
          separator: widget.mInitPara[HttpParamKeyValue.PARAM_KEY_SEPARATOR] ??
              BasStringValueConstant.STR_COMMON_COLON_A_COLON);
    }
  }

  /*
   * 查询表格所有的列
   */
  List<DataColumn> queryDataColumn()
  {
    List<DataColumn> list = [];
    for (int i = 0; i < mFldList.length; i++)
    {
      Fld fld = mFldList[i];
      if (filterFldItem(fld))
      {
        list.add(DataColumn(label: Text(fld.getNamec()), numeric: true, onSort: (int columnIndex, bool ascending)
        =>
            sort<dynamic>((dynamic d)
            => d[fld.getColname()], columnIndex, ascending)));
      }
    }
    return list;
  }

  /*
   * 表格头排序
   */
  void sort<T>(Comparable<T> getField(dynamic d), int columnIndex, bool ascending)
  {
    mDataSource._sort<T>(getField, ascending);
    setState(()
    {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;
    });
  }

  /*
   * 是否过滤fld的条目
   * @param fld listview中一个条目生成的item值
   * return [false=过滤]
   */
  bool filterFldItem(Fld fld)
  {
    if (fld.getDisporder() > DigitValueConstant.APP_DIGIT_VALUE_0)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  /*
   * 获取选中的数据
   */
  dynamic querySelect()
  {
    List<dynamic> list = [];
    mDataSource.dataCell.forEach((item)
    {
      if (item[BasMapKeyConstant.MAP_KEY_SELECT] != null && item[BasMapKeyConstant.MAP_KEY_SELECT])
      {
        list.add(item);
      }
    });
    return list;
  }

  dynamic querySelectOld()
  {
    List<dynamic> list = [];
    widget.mInitPara[BasMapKeyConstant.MAP_KEY_LIST].forEach((item)
    {
      if (item[BasMapKeyConstant.MAP_KEY_SELECT] != null && item[BasMapKeyConstant.MAP_KEY_SELECT])
      {
        list.add(item);
      }
    });
    return list;
  }
}

/*
 * 表格控件数据源(可以作为基类进行继承)---多选
 * @param {Object 必传} major 主类型
 */
class DataSource extends DataTableSource
{
  /*
   * 数据集
   */
  dynamic dataCell;

  /*
   * 当前属性的列
   */
  List<Fld> mFldList;

  /*
   * 表格控件被选中的数量
   */
  int _selectedCount = 0;

  DataSource(this.dataCell, this.mFldList);

  @override
  DataRow getRow(int index)
  {
    if (index >= dataCell.length) return null;
    final dynamic cell = dataCell[index];
    return DataRow.byIndex(
        index: index,
        selected: cell[BasMapKeyConstant.MAP_KEY_SELECT] ?? false,
        onSelectChanged: (bool value)
        {
          if (cell[BasMapKeyConstant.MAP_KEY_SELECT] != value)
          {
            _selectedCount += value ? 1 : -1;
            assert(_selectedCount >= 0);
            cell[BasMapKeyConstant.MAP_KEY_SELECT] = value;
            notifyListeners();
          }
        },
        cells: queryDataCell(cell));
  }

  /*
   * 查询表格所有值
   */
  List<DataCell> queryDataCell(cell)
  {
    List<DataCell> list = [];
    for (int j = 0; j < mFldList.length; j++)
    {
      Fld fld = mFldList[j];
      if (filterFldItem(fld))
      {
        list.add(DataCell(Text(cell[fld.getColname()].toString())));
      }
    }
    return list;
  }

  /*
   * 是否过滤fld的条目
   * @param fld listview中一个条目生成的item值
   * return [false=过滤]
   */
  bool filterFldItem(Fld fld)
  {
    if (fld.getDisporder() > DigitValueConstant.APP_DIGIT_VALUE_0)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

  /*
   * ascending 上升 数据排序
   */
  void _sort<T>(Comparable<T> getField(dynamic d), bool ascending)
  {
    dataCell.sort((dynamic a, dynamic b)
    {
      if (!ascending)
      {
        final dynamic c = a;
        a = b;
        b = c;
      }
      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    notifyListeners();
  }

  /*
   * 选择表格中所有数据
   */
  void selectAll(bool checked)
  {
    for (dynamic cell in dataCell)
    {
      cell[BasMapKeyConstant.MAP_KEY_SELECT] = checked;
    }
    _selectedCount = checked ? dataCell.length : 0;
    notifyListeners();
  }

  @override
  bool get isRowCountApproximate
  => false;

  /*
   * 总行数
   */
  @override
  int get rowCount
  => dataCell.length;

  /*
   * 表格控件被选中多少个
   */
  @override
  int get selectedRowCount
  => _selectedCount;
}


/*
 * 表格控件数据源(可以作为基类进行继承)---单选
 * @param {Object 必传} major 主类型
 */
class SingleDataSource extends DataSource
{

  SingleDataSource(dataCell, List<Fld> mFldList) : super(dataCell, mFldList);

  @override
  DataRow getRow(int index)
  {
    if (index >= dataCell.length) return null;
    final dynamic cell = dataCell[index];
    return DataRow.byIndex(
        index: index,
        selected: cell[BasMapKeyConstant.MAP_KEY_SELECT] ?? false,
        onSelectChanged: (bool value)
        {
          if (cell[BasMapKeyConstant.MAP_KEY_SELECT] != value)
          {
            _selectedCount = 1;
            dataCell.forEach((item)
            {
              if(item == cell)
              {
                cell[BasMapKeyConstant.MAP_KEY_SELECT] = value;
              }
              else
              {
                item[BasMapKeyConstant.MAP_KEY_SELECT] = false;
              }
            });
            notifyListeners();
          }
        },
        cells: queryDataCell(cell));
  }

  /*
   * 选择表格中所有数据
   */
  void selectAll(bool checked)
  {
  }
}